package com.sikong.geotools.quickstart;

import org.geotools.data.DataUtilities;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.collection.SpatialIndexFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.map.FeatureLayer;
import org.geotools.map.MapContent;
import org.geotools.styling.SLD;
import org.geotools.styling.Style;
import org.geotools.swing.JMapFrame;
import org.geotools.swing.data.JFileDataStoreChooser;

import javax.swing.*;
import java.io.File;
import java.io.IOException;

/**
 * 这是一段基于Geotools展示shp数据的代码
 *
 * @see <a href="https://docs.geotools.org/latest/userguide/tutorial/quickstart/intellij.html">Quick-Start</a>
 *
 * @author 梁超 / stan
 * @since  0.1.0
 * @Date   2022/03/08
 */
public class Mapshow {

    /**
     * 将数据缓存在内存中
     */
    public void showByCache() throws IOException, UnsupportedLookAndFeelException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        File file = JFileDataStoreChooser.showOpenFile("shp", new File("src/main/resources"), null);
        if (file == null) {
            return;
        }

        FileDataStore dataStore = FileDataStoreFinder.getDataStore(file);
        SimpleFeatureSource featureSource = dataStore.getFeatureSource();

        SimpleFeatureSource cachedSource = DataUtilities.source(new SpatialIndexFeatureCollection(featureSource.getFeatures()));
        MapContent mapContent = new MapContent();
        mapContent.setTitle("Quickstart by Cache");

        Style style = SLD.createSimpleStyle(cachedSource.getSchema());
        FeatureLayer featureLayer = new FeatureLayer(cachedSource, style);
        mapContent.addLayer(featureLayer);

        JMapFrame.showMap(mapContent);
    }

    /**
     * 直接从磁盘读取数据
     */
    public void showByDisk() throws IOException, UnsupportedLookAndFeelException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        File file = JFileDataStoreChooser.showOpenFile("shp", new File("src/main/resources"), null);
        if (file == null) {
            return;
        }

        FileDataStore dataStore = FileDataStoreFinder.getDataStore(file);
        SimpleFeatureSource featureSource = dataStore.getFeatureSource();

        MapContent mapContent = new MapContent();
        mapContent.setTitle("Quickstart by Disk");

        Style style = SLD.createSimpleStyle(featureSource.getSchema());
        FeatureLayer layer = new FeatureLayer(featureSource, style);
        mapContent.addLayer(layer);

        JMapFrame.showMap(mapContent);
    }

}
